#include "DbManager.h"

static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
    int i;
    for (i = 0; i < argc; i++) {
        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
    printf("\n");
    return 0;
}

/*
 * Usage:
 * 本模块用于供用户创建数据库并添加到数据库的访问路由
 */

void DbManager(const char *dbPathConfig) {
    string dbPath = string(dbPathConfig);

    sqlite3 *db;
    char *zErrMsg;
    int rc;
    string sql;

    rc = sqlite3_open(dbPath.c_str(), &db);

    if (rc) {
        printf("[ERROR] 无法加载数据库: %s\n", sqlite3_errmsg(db));
        return;
    } else {
        printf("[INFO] 成功加载数据库\n");
    }

    string tableName;
    string colsInfo;
    printf("[INFO] 请输入表名，表名只能包含英文字符、数字及下划线\n");
    getline(cin, tableName);
    printf("[INFO] 请输入列信息，每一列以英文逗号分隔，例如\"id integer unique, content string\"\n");
    getline(cin, colsInfo);

    string createInstr = "CREATE TABLE " + tableName + "(" + colsInfo + ");";
    // cout << createInstr;
    /* Execute SQL statement */
    rc = sqlite3_exec(db, createInstr.c_str(), callback, nullptr, &zErrMsg);
    if (rc != SQLITE_OK) {
        printf("[ERROR] SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    } else {
        printf("[INFO] 成功创建表：%s\n", tableName.c_str());
    }
    FILE *f_table = fopen("Config/TableName.txt", "a");
    if (f_table == nullptr) {
	f_table = fopen("Config/TableName.txt", "w");
    }
    fprintf(f_table, "%s\n", tableName.c_str());
    fclose(f_table);
    sqlite3_close(db);
}
